package org.ihelpuoo.orm;

import java.io.File;
import java.util.Map;

import org.ihelpuoo.orm.filter.Filter;
import org.ihelpuoo.orm.filter.StringObjectFilter;

public abstract class ObjectManager
{

	protected Map<String, Object>	objects;
	protected III					iii;
	protected File					dir;
	private String					pattern;
	private Class					type;

	protected ObjectManager(III iii, File dir, String pattern, Class type) throws IIIException
	{
		this.iii = iii;
		this.dir = dir;
		this.pattern = pattern;
		this.type = type;
		this.init();
	}

	protected void init() throws IIIException
	{
		if (!dir.exists())
			throw new IIIException("Path \"" + dir.getName() + "\" doesn't existed!");
		if (!dir.isDirectory())
			throw new IIIException("Path \"" + dir.getName() + "\" should be a directory!");
		Filter filter = new StringObjectFilter(pattern);
		try
		{
			objects = iii.buildMap(dir,type,filter,null,null,null,null);
		}
		catch (Exception e)
		{
			throw IIIException.wrap(e);
		}
	}

	public Object getObject(String name)
	{
		return objects.get(name);
	}

	public synchronized void clear()
	{
		objects.clear();
	}

	public synchronized void refresh() throws IIIException
	{
		init();
	}
}
